package com.anguin.mylibrary.controller;

import com.anguin.mylibrary.service.ex.*;
import com.anguin.mylibrary.util.JsonResult;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class BaseController
{
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e)
    {
        System.out.println("捕获到异常：" + e.getMessage()); // 调试用日志
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof UsernameDuplicatedException)
        {
            result.setCode(4000);
            result.setMessage("用户名被占用");
        } else if (e instanceof InsertException)
        {
            result.setCode(5000);
            result.setMessage("注册时产生未知异常");
        } else if (e instanceof UserNotFoundException)
        {
            result.setCode(5001);
            result.setMessage("用户数据不存在");
        } else if (e instanceof PasswordNotMatchException)
        {
            result.setCode(5002);
            result.setMessage("密码未匹配");
//            System.out.println(1);
        } else if (e instanceof UpdateException)
        {
            result.setCode(5003);
            result.setMessage("用户更新时失败");
        } else if (e instanceof EmailDuplicatedException)
        {
            result.setCode(5003);
            result.setMessage("邮箱被占用");
        } else if (e instanceof PhoneNumberDuplicatedException)
        {
            result.setCode(5004);
            result.setMessage("电话号码被占用");
        } else if (e instanceof SessionExpiration)
        {
            result.setCode(5005);
            result.setMessage("会话过期");
        } else if (e instanceof GetDataException)
        {
            result.setCode(5006);
            result.setMessage("获取数据失败");
        } else
        {
            result.setCode(500);
            result.setMessage("未知错误");
        }
        return result;
    }

    protected final String getUsernameFromSession(HttpSession session)
    {
        return session.getAttribute("username").toString();
    }

    protected final Integer getUidFromSession(HttpSession session)
    {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }
}
